package com.example.minio_demo.controller;

import com.example.minio_demo.template.MinioTemplate;
import com.example.minio_demo.util.HttpsClientUtil;
import lombok.AllArgsConstructor;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * @author benjamin_5
 * @Description
 * @date 2023/8/31
 */
@RestController
@RequestMapping("download")
@AllArgsConstructor
public class DownLoadController {

    private static final String minioUrl = "http://127.0.0.1:9000/test/";
    private static final String fileName = "123.mp4";

    @GetMapping("video")
    public void downloadVideo(HttpServletResponse response) throws Exception {
        String fileUrl = minioUrl + fileName;
        byte[] byteResult = HttpsClientUtil.getByteResult(fileUrl, null);
        // 设置响应头信息
        response.setHeader("Content-Disposition", "attachment;filename="+fileName);
        //response.setContentType("video/mp4");
        // 在响应头里加上自定义字符串
        response.addHeader("X-sign", "MEsasda123151231asdgasdad");

        assert byteResult != null;
        InputStream inputStream = new ByteArrayInputStream(byteResult);
        Path tempFile = Files.createTempFile(fileName, null);

        Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
        // 复制视频文件到输出流
        Files.copy(tempFile.toAbsolutePath(), response.getOutputStream());

    }

    @GetMapping("get")
    public String getUrl() throws Exception {
        // Get API url
        String url = "http://localhost:8080/download/video";
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        Header header = response.getFirstHeader("X-sign");
        String value = header.getValue();
        System.out.println("X-sign: "+value);
        HttpEntity entity = response.getEntity();
        InputStream videoStream = entity.getContent();
        FileOutputStream output = new FileOutputStream("/Users/wuhanxue/Downloads/video.mp4");
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = videoStream.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
        output.close();
        videoStream.close();
        return value;
    }



}
